package island

import (
	"fmt"
	"os"
	"path/filepath"
	"syscall"
)

func getOverlayPaths(id string) (string, string, string) {
	work := filepath.Join(containerRootDir, id, "work")
	upper := filepath.Join(containerRootDir, id, "upper")
	rootfs := filepath.Join(containerRootDir, id, "rootfs")

	return work, upper, rootfs
}

// 创建三个 overlay dir
func overlayCreate(id string) error {
	work, upper, rootfs := getOverlayPaths(id)

	paths := []string{work, upper, rootfs}

	for idx := range paths {
		p := paths[idx]
		if err := os.MkdirAll(p, 0755); err != nil {
			_ = overlayClean(id)
			return err
		}
	}
	return nil
}

func overlayMount(id string, imagePath string) error {
	initPath := filepath.Join(containerRootDir, id, "init")
	lowerDir := imagePath + ":" + initPath
	workDir, upperDir, mergeDir := getOverlayPaths(id)
	opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir)
	if err := syscall.Mount("overlay", mergeDir, "overlay", 0, opts); err != nil {
		return err
	}

	// 注册overlay信息
	overlayInfo.register(id)
	return nil
}

func overlayClean(id string) error {
	work, upper, rootfs := getOverlayPaths(id)
	paths := []string{work, upper, rootfs}
	for idx := range paths {
		// path 不存在 err 不会报错
		if err := os.RemoveAll(paths[idx]); err != nil {
			return err
		}
	}

	return nil
}

func overlayUnmount(id string) error {
	_, _, path := getOverlayPaths(id)
	if err := syscall.Unmount(path, 0); err != nil {
		return err
	}

	// 取消overlay Mount Info
	overlayInfo.unRegister(id)
	return nil
}
